package biz.datalk.industrialland.admin.modules.online.dynform.service.impl;

import biz.datalk.commons.utils.MapUtil;
import biz.datalk.commons.utils.json.JsonUtil;
import biz.datalk.industrialland.admin.modules.common.servie.ICommonService;
import biz.datalk.industrialland.admin.modules.online.config.cfg.enums.SqlOperationTypeEnum;
import biz.datalk.industrialland.admin.modules.online.config.hook.HookSplicingResult;
import biz.datalk.industrialland.admin.modules.online.config.hook.HookValidParamsResult;
import biz.datalk.industrialland.admin.modules.online.config.hook.IDynfromHook;
import biz.datalk.industrialland.admin.modules.online.config.util.DynformFieldUtil;
import biz.datalk.industrialland.admin.modules.online.config.util.DynfromEnhanceJsUtil;
import biz.datalk.industrialland.admin.modules.online.config.util.HookUtil;
import biz.datalk.industrialland.admin.modules.online.dynform.mapper.IDynformFieldMapper;
import biz.datalk.industrialland.admin.modules.online.dynform.mapper.IDynformHeadMapper;
import biz.datalk.industrialland.admin.modules.online.dynform.pojo.dto.DictItem;
import biz.datalk.industrialland.admin.modules.online.dynform.pojo.dto.DynformAutoDTO;
import biz.datalk.industrialland.admin.modules.online.dynform.pojo.dto.DynformFieldDTO;
import biz.datalk.industrialland.admin.modules.online.dynform.pojo.dto.DynformHeadDTO;
import biz.datalk.industrialland.admin.modules.online.dynform.pojo.po.DynformEnhanceJs;
import biz.datalk.industrialland.admin.modules.online.dynform.pojo.po.DynformField;
import biz.datalk.industrialland.admin.modules.online.dynform.pojo.po.DynformFieldExample;
import biz.datalk.industrialland.admin.modules.online.dynform.pojo.po.DynformHead;
import biz.datalk.industrialland.admin.modules.online.dynform.service.IDynformAutoService;
import biz.datalk.industrialland.admin.modules.online.dynform.service.IDynformEnhanceJsService;
import biz.datalk.industrialland.common.def.enums.DBYNEnum;
import biz.datalk.industrialland.common.result.UnifyResult;
import biz.datalk.industrialland.common.util.FieldUtil;
import biz.datalk.industrialland.common.util.SpringContextUtils;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author tarofang@163.com
 * @date 2019-12-19
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class DynformAutoServiceImpl implements IDynformAutoService {

    private final ICommonService commonService;

    private final IDynformHeadMapper dynformHeadMapper;

    private final IDynformFieldMapper dynformFieldMapper;

    private IDynformEnhanceJsService dynformEnhanceJsService;

    @Autowired
    public DynformAutoServiceImpl(ICommonService commonService, IDynformHeadMapper dynformHeadMapper, IDynformFieldMapper dynformFieldMapper) {
        this.commonService = commonService;
        this.dynformHeadMapper = dynformHeadMapper;
        this.dynformFieldMapper = dynformFieldMapper;
    }

    @Autowired
    public void setDynformEnhanceJsService(IDynformEnhanceJsService dynformEnhanceJsService) {
        this.dynformEnhanceJsService = dynformEnhanceJsService;
    }

    @Override
    public UnifyResult list(DynformAutoDTO dynformAutoDTO) {
        String tableId = dynformAutoDTO.getTableId();
        DynformHead table = dynformHeadMapper.selectByPrimaryKey(tableId);
        if (table == null) {
            return UnifyResult.fail("查询的表不存在");
        }

        IDynfromHook hook = HookUtil.newInstance(table.getHookImplClass());

        hook.beforeList(dynformAutoDTO);

        // 获取查询参数
        // String queryParams = dynformAutoDTO.getQueryParams();
        // Map<String, String> queryMap = JsonUtil.json2JavaBean(queryParams, new TypeToken<Map<String, String>>() {}.getType());
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();

        List<DynformFieldDTO> existsFields = getTableAllField(tableId);
        Map<String, String> queryMap = hook.parseQueryParams(dynformAutoDTO, request, table, existsFields, SqlOperationTypeEnum.LIST_ROWS);

        HookSplicingResult rowRes = hook.splicingListRowSql(table, queryMap, dynformAutoDTO, existsFields);
        @SuppressWarnings("unchecked") List<Map<String, Object>> rows = (List<Map<String, Object>>) hook.execSql(rowRes.getSql(), rowRes.getArgs(), SqlOperationTypeEnum.LIST_ROWS);
        rows = CollectionUtils.isNotEmpty(rows) ? rows : new ArrayList<>();
        // 下划线转驼峰
        rows = MapUtil.underline2Hump(rows);
        // 字典转换
        convertDict(rows, existsFields);

        List<DynformFieldDTO> pageShowListFields = getPageShowListFields(existsFields);
        Map<String, DynformFieldDTO> dtoMap = DynformFieldUtil.fieldNameHumpKeyMap(pageShowListFields, false);
        for (Map<String, Object> row : rows) {
            for (Map.Entry<String, Object> entry : row.entrySet()) {
                DynformFieldDTO dto = dtoMap.get(entry.getKey());
                if (dto == null) {
                    continue;
                }
                if (StringUtils.equalsAnyIgnoreCase(dto.getFieldType(), "datetime", "timestamp")) {
                    Object val = entry.getValue();
                    if (!(val instanceof Date)) {
                        continue;
                    }
                    if (StringUtils.equalsIgnoreCase(dto.getPageShowType(), "date")) {
                        entry.setValue(DateFormatUtils.format((Date) val, "yyyy-MM-dd"));
                    }
                    if (StringUtils.equalsIgnoreCase(dto.getPageShowType(), "datetime")) {
                        entry.setValue(DateFormatUtils.format((Date) val, "yyyy-MM-dd HH:mm:ss"));
                    }
                }
            }
        }

        HookSplicingResult totalRes = hook.splicingListTotalSql(table, queryMap, dynformAutoDTO, existsFields);
        Long total = (Long) hook.execSql(totalRes.getSql(), totalRes.getArgs(), SqlOperationTypeEnum.LIST_TOTAL);


        UnifyResult result = UnifyResult.success().mapData().put("rows", rows).put("total", total);
        return hook.afterList(dynformAutoDTO, result);


        // List<DynformField> queryFieldList = getQueryFields(existsFields);
        // ListHelper listHelper = ListHelper.create();
        // StringBuilder sb = new StringBuilder();
        // for (Map.Entry<String, String> entry : queryMap.entrySet()) {
        //     if (StringUtils.isBlank(entry.getValue())) {
        //         continue;
        //     }
        //     String key = entry.getKey();
        //     key = FieldUtil.hump2Underline(key);
        //     DynformField one = listHelper.findOne(queryFieldList, "getFieldName", key, DynformField.class, String.class);
        //     if (one == null) {
        //         continue;
        //     }
        //     // varchar/int/double/datetime/timestamp/decimal/text/mediumtext/blob
        //     // String fieldType = one.getFieldType();
        //     // qeuryResMap.put(key, entry.getValue());
        //     Object val = null;
        //     switch (one.getFieldType()) {
        //         case "varchar":
        //         case "text":
        //         case "mediumtext":
        //         case "datetime":
        //         case "timestamp":
        //             val = entry.getValue();
        //             break;
        //         case "int":
        //             val = Integer.valueOf(entry.getValue());
        //             break;
        //         case "double":
        //             val = Double.valueOf(entry.getValue());
        //             break;
        //         default:
        //             break;
        //     }
        //     if (val == null) {
        //         continue;
        //     }
        //     if (sb.length() > 0) {
        //         sb.append(" AND ");
        //     }
        //     sb.append(key);
        //     if (val instanceof String) {
        //         String str = (String) val;
        //         if (str.startsWith("*") || str.endsWith("*")) {
        //             str = str.startsWith("*") ? "%" + str.substring(1) : str;
        //             str = str.endsWith("*") ? str.substring(0, str.length() - 1) + "%" : str;
        //             sb.append(" LIKE ").append("'").append(str).append("'");
        //         } else {
        //             sb.append("=").append("'").append(val).append("'");
        //         }
        //     } else {
        //         sb.append("=").append(val);
        //     }
        // }
        //
        // List<DynformField> pageShowListFields = getPageShowListFields(existsFields);
        // if (CollectionUtils.isEmpty(pageShowListFields)) {
        //     return UnifyResult.fail("未设置列表显示字段");
        // }
        // List<String> fields = listHelper.getValList(pageShowListFields, "getFieldName", DynformField.class, String.class);
        // String queryFields = listHelper.combine(fields, ",");
        //
        //
        // String dataSQL = "SELECT " + queryFields + " FROM " + table.getTableName() + " ";
        // String countSQL = "SELECT COUNT(*) FROM " + table.getTableName();
        // if (sb.length() > 0) {
        //     dataSQL += " WHERE " + sb.toString();
        //     countSQL += " WHERE " + sb.toString();
        // }
        //
        // long total = commonService.getCountForJdbc(countSQL);
        //
        // if (StringUtils.equals(table.getIsPagination(), DBYNEnum.Y.name())) {
        //     int offset = (dynformAutoDTO.getPageNumber() - 1) * dynformAutoDTO.getPageSize();
        //     dataSQL = dataSQL.concat(" LIMIT ") + offset + "," + dynformAutoDTO.getPageSize();
        // }
        // List<Map<String, Object>> rows = commonService.findForJdbc(dataSQL);
        // rows = CollectionUtils.isNotEmpty(rows) ? rows : new ArrayList<>();
        //
        // rows = MapUtil.underline2Hump(rows);
        //
        // // 字典转换
        // if (CollectionUtils.isNotEmpty(rows)) {
        //     Map<String, List<DictItem>> fieldDicts = getFieldDicts(pageShowListFields);
        //     List<DictItem> dictItems = null;
        //     String key = null;
        //     Object val = null;
        //     for (Map<String, Object> row : rows) {
        //         dictItems = null;
        //         key = null;
        //         for (Map.Entry<String, Object> entry : row.entrySet()) {
        //             val = entry.getValue();
        //             if (val == null) {
        //                 continue;
        //             }
        //             key = entry.getKey();
        //             dictItems = fieldDicts.get(key);
        //             if (CollectionUtils.isEmpty(dictItems)) {
        //                 continue;
        //             }
        //             for (DictItem dict : dictItems) {
        //                 if (StringUtils.equals(dict.getCode(), String.valueOf(val))) {
        //                     entry.setValue(dict.getText());
        //                     break;
        //                 }
        //             }
        //         }
        //     }
        // }
        //
        //
        // return UnifyResult.success().mapData().put("rows", rows).put("total", total);
    }

    private void convertDict(List<Map<String, Object>> rows, List<DynformFieldDTO> existsFields) {
        List<DynformFieldDTO> pageShowListFields = getPageShowListFields(existsFields);
        Map<String, List<DictItem>> fieldDicts = getFieldDicts(pageShowListFields);
        for (Map<String, Object> row : rows) {
            convertDict(row, fieldDicts);
        }
    }

    private void convertDict(Map<String, Object> row, Map<String, List<DictItem>> fieldDicts) {
        List<DictItem> dictItems = null;
        String key = null;
        Object val = null;
        for (Map.Entry<String, Object> entry : row.entrySet()) {
            val = entry.getValue();
            if (val == null) {
                continue;
            }
            key = entry.getKey();
            dictItems = fieldDicts.get(key);
            if (CollectionUtils.isEmpty(dictItems)) {
                continue;
            }
            for (DictItem dict : dictItems) {
                if (StringUtils.equals(dict.getCode(), String.valueOf(val))) {
                    entry.setValue(dict.getText());
                    break;
                }
            }
        }
    }

    private Map<String, List<DictItem>> getFieldDicts(List<DynformFieldDTO> fields) {
        Map<String, List<DictItem>> fieldDicts = new HashMap<>(4);
        for (DynformFieldDTO field : fields) {
            String dictTable = StringUtils.trimToEmpty(field.getDictTable());
            String dictCode = StringUtils.trimToEmpty(field.getDictCode());
            String dictText = StringUtils.trimToEmpty(field.getDictText());
            if (StringUtils.isNotEmpty(dictCode) && StringUtils.isAllEmpty(dictTable, dictText)) {
                List<DictItem> dicts = commonService.selectDictFromSysdict(dictCode);
                if (CollectionUtils.isNotEmpty(dicts)) {
                    fieldDicts.put(FieldUtil.underline2Hump(field.getFieldName()), dicts);
                }
                continue;
            }
            // 从 {dictTable} 表中获取数据
            if (StringUtils.isNotEmpty(dictTable) && StringUtils.isNotEmpty(dictCode) && StringUtils.isNotEmpty(dictText)) {
                List<DictItem> dicts = commonService.selectDictFromCustomTable(dictTable, dictCode, dictText);
                if (CollectionUtils.isNotEmpty(dicts)) {
                    fieldDicts.put(FieldUtil.underline2Hump(field.getFieldName()), dicts);
                }
                continue;
            }
        }
        return fieldDicts;
    }

    @Override
    public UnifyResult detail(DynformAutoDTO dynformAutoDTO) {
        String tableId = dynformAutoDTO.getTableId();
        DynformHead table = dynformHeadMapper.selectByPrimaryKey(tableId);
        if (table == null) {
            return UnifyResult.fail("提交的数据有误");
        }

        IDynfromHook hook = HookUtil.newInstance(table.getHookImplClass());
        hook.beforeDetail(dynformAutoDTO);

        List<DynformFieldDTO> tableAllField = getTableAllField(tableId);

        HookSplicingResult hookSplicingResult = hook.splicingDetailSql(table, dynformAutoDTO, tableAllField);
        @SuppressWarnings("unchecked") Map<String, Object> resMap = (Map<String, Object>) hook.execSql(hookSplicingResult.getSql(), hookSplicingResult.getArgs(), SqlOperationTypeEnum.DETAIL);
        if (resMap == null) {
            return UnifyResult.fail("未查询到相关数据");
        }
        resMap = MapUtil.underline2Hump(resMap);

        // 数据修正
        Map<String, DynformFieldDTO> dtoMap = DynformFieldUtil.fieldNameHumpKeyMap(tableAllField, false);
        for (Map.Entry<String, Object> entry : resMap.entrySet()) {
            DynformFieldDTO dto = dtoMap.get(entry.getKey());
            if (dto == null) {
                continue;
            }
            if (StringUtils.equalsAnyIgnoreCase(dto.getFieldType(), "datetime", "timestamp")) {
                Object val = entry.getValue();
                if (!(val instanceof Date)) {
                    continue;
                }
                if (StringUtils.equalsIgnoreCase(dto.getPageShowType(), "date")) {
                    entry.setValue(DateFormatUtils.format((Date) val, "yyyy-MM-dd"));
                }
                if (StringUtils.equalsIgnoreCase(dto.getPageShowType(), "datetime")) {
                    entry.setValue(DateFormatUtils.format((Date) val, "yyyy-MM-dd HH:mm:ss"));
                }
            }
        }

        // List<DynformField> existsFields = getExistsFields(tableId);
        // List<DynformField> pageShowFields = getPageShowFields(existsFields, Boolean.TRUE);
        // ListHelper listHelper = ListHelper.create();
        // List<String> fields = listHelper.getValList(pageShowFields, "getFieldName", DynformField.class, String.class);
        // String fieldStr = listHelper.combine(fields, ",");
        //
        // String sql = "SELECT " + fieldStr + " FROM " + table.getTableName() + " WHERE id=?";
        //
        // Map<String, Object> resMap = commonService.findOneForJdbc(sql, dynformAutoDTO.getId());
        // if (resMap == null) {
        //     return UnifyResult.fail("未查询到相关数据");
        // }
        //
        // resMap = MapUtil.underline2Hump(resMap);
        ;


        UnifyResult result = UnifyResult.success().setData(resMap);
        return hook.afterDetail(dynformAutoDTO, result);
    }

    @Override
    public UnifyResult add(DynformAutoDTO dynformAutoDTO) {
        return handleSave(dynformAutoDTO, Boolean.FALSE);
    }

    @Override
    public UnifyResult edit(DynformAutoDTO dynformAutoDTO) {
        return handleSave(dynformAutoDTO, Boolean.TRUE);
    }

    private UnifyResult handleSave(DynformAutoDTO dynformAutoDTO, boolean isUpdate) {
        String tableId = dynformAutoDTO.getTableId();
        DynformHead table = dynformHeadMapper.selectByPrimaryKey(tableId);
        if (table == null) {
            log.debug("Invalid talbleId: [{}]", tableId);
            return UnifyResult.fail("提交的数据有误");
        }

        IDynfromHook hook = HookUtil.newInstance(table.getHookImplClass());
        if (isUpdate) {
            hook.beforeUpdate(dynformAutoDTO);
        } else {
            hook.beforeInsert(dynformAutoDTO);
        }

        // String jsonParams = dynformAutoDTO.getParams();
        // Map<String, String> paramsMap = JsonUtil.json2JavaBean(jsonParams, new TypeToken<Map<String, String>>() {}.getType());
        List<DynformFieldDTO> existsFields = getTableAllField(tableId);

        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        Map<String, String> paramsMap = hook.parseParams(dynformAutoDTO, request, table, existsFields, isUpdate ? SqlOperationTypeEnum.UPDATE : SqlOperationTypeEnum.INSERT);
        if (paramsMap == null || paramsMap.isEmpty()) {
            log.debug("Invalid params: [{}]", dynformAutoDTO.getParams());
            return UnifyResult.fail("提交的数据有误");
        }

        // 参数验证
        HookValidParamsResult validParamsResult = hook.validParams(dynformAutoDTO, table, existsFields, paramsMap, isUpdate ? SqlOperationTypeEnum.UPDATE : SqlOperationTypeEnum.INSERT);

        // @formatter:off
        HookSplicingResult hookSplicingResult = isUpdate
                ? hook.splicingUpdateSql(table, dynformAutoDTO, existsFields, validParamsResult)
                : hook.splicingInsertSql(table, dynformAutoDTO, existsFields, validParamsResult);
        // @formatter:on
        Integer resInt = (Integer) hook.execSql(hookSplicingResult.getSql(), hookSplicingResult.getArgs(), isUpdate ? SqlOperationTypeEnum.UPDATE : SqlOperationTypeEnum.INSERT);

        // StringBuilder sqlsb = new StringBuilder();
        // List<Object> args = new ArrayList<>();
        // boolean isFirst = true;
        // // 新增数据
        // if (!isUpdate) {
        //     // String sql = "INSERT INTO "+ table.getTableName() +" (%s) values (%s)";
        //     sqlsb.append("INSERT INTO ").append(table.getTableName()).append("(");
        //     for (Map.Entry<String, Object> entry : fvPkMap.entrySet()) {
        //         if (!isFirst) {
        //             sqlsb.append(",");
        //         } else {
        //             isFirst = false;
        //         }
        //         sqlsb.append(entry.getKey());
        //         args.add(IdProvider.createUUIDId());
        //     }
        //     for (Map.Entry<String, Object> entry : fvMap.entrySet()) {
        //         if (!isFirst) {
        //             sqlsb.append(",");
        //         } else {
        //             isFirst = false;
        //         }
        //         sqlsb.append(entry.getKey());
        //         args.add(entry.getValue());
        //     }
        //     sqlsb.append(") values (");
        //     for (int index = 0, size = args.size(); index < size; index++) {
        //         if (index > 0) {
        //             sqlsb.append(",");
        //         }
        //         sqlsb.append("?");
        //     }
        //     sqlsb.append(")");
        // } else {
        //     // 更新数据
        //     // UPDATE %s SET f1=v,f2=x WHERE pk1=x1 AND pk2=x2
        //     sqlsb.append("UPDATE ").append(table.getTableName()).append(" SET ");
        //     for (Map.Entry<String, Object> entry : fvMap.entrySet()) {
        //         if (!isFirst) {
        //             sqlsb.append(",");
        //         } else {
        //             isFirst = false;
        //         }
        //         sqlsb.append(entry.getKey()).append("=?");
        //         args.add(entry.getValue());
        //     }
        //     sqlsb.append(" WHERE ");
        //     isFirst = true;
        //     for (Map.Entry<String, Object> entry : fvPkMap.entrySet()) {
        //         if (!isFirst) {
        //             sqlsb.append(" AND ");
        //         } else {
        //             isFirst = false;
        //         }
        //         sqlsb.append(entry.getKey()).append("=?");
        //         args.add(entry.getValue());
        //     }
        // }
        //
        // int resInt = commonService.update(sqlsb.toString(), args.toArray());

        return isUpdate ? hook.afterUpdate(dynformAutoDTO, UnifyResult.success()) : hook.afterInsert(dynformAutoDTO, UnifyResult.success());
    }


    @Override
    public UnifyResult delete(DynformAutoDTO dynformAutoDTO) {
        // String idsSeparator = ",";
        // String ids = StringUtils.trimToNull(dynformAutoDTO.getIds());
        // if (StringUtils.isEmpty(ids) || ids.startsWith(idsSeparator) || ids.endsWith(idsSeparator)) {
        //     return UnifyResult.fail("提交的数据有误");
        // }
        // if (StringUtils.isBlank(dynformAutoDTO.getId())) {
        //     return UnifyResult.fail("提交的数据有误");
        // }

        String tableId = dynformAutoDTO.getTableId();
        DynformHead table = dynformHeadMapper.selectByPrimaryKey(tableId);
        if (table == null) {
            return UnifyResult.fail("提交的数据有误");
        }

        IDynfromHook hook = HookUtil.newInstance(table.getHookImplClass());
        hook.beforeDelete(dynformAutoDTO);

        List<DynformFieldDTO> tableAllField = getTableAllField(tableId);

        HookSplicingResult hookSplicingResult = hook.splicingDeleteSql(table, dynformAutoDTO, tableAllField);
        int resInt = (int) hook.execSql(hookSplicingResult.getSql(), hookSplicingResult.getArgs(), SqlOperationTypeEnum.DELETE);

        if (resInt != 1) {
            return UnifyResult.fail("删除失败");
        }

        // String sql = "DELETE FROM " + table.getTableName() + " WHERE id=?";
        // int resInt = commonService.update(sql, dynformAutoDTO.getId().trim());
        // if (resInt != 1) {
        //     return UnifyResult.fail("删除失败");
        // }

        return hook.afterDelete(dynformAutoDTO, UnifyResult.success());
    }

    @Override
    public UnifyResult doButton(DynformAutoDTO dynformAutoDTO) {
        String tableId = dynformAutoDTO.getTableId();
        DynformHead table = dynformHeadMapper.selectByPrimaryKey(tableId);
        if (table == null) {
            return UnifyResult.fail("未找到表配置信息");
        }
        DynformHeadDTO tableDTO = new DynformHeadDTO();
        BeanUtils.copyProperties(table, tableDTO);

        // @formatter:off
        Map<String, String> paramsMap = JsonUtil.json2JavaBean(dynformAutoDTO.getParams(), new TypeToken<Map<String, String>>() {}.getType());
        // @formatter:on
        if (MapUtils.isEmpty(paramsMap)) {
            return UnifyResult.fail("未提交有效数据");
        }

        String btnCode = StringUtils.trimToEmpty(dynformAutoDTO.getBtnCode());
        if (StringUtils.isEmpty(btnCode)) {
            return UnifyResult.fail("未提交有效数据");
        }

        IDynfromHook hook = HookUtil.newInstance(table.getHookImplClass());
        hook.beforeDoButton(dynformAutoDTO);

        tableDTO.setAllFields(getTableAllField(tableId));
        UnifyResult result = hook.doButton(tableDTO, btnCode, paramsMap);

        return hook.afterDoButton(dynformAutoDTO, result);
    }

    @Override
    public UnifyResult enhanceJs(DynformAutoDTO dynformAutoDTO) {
        String tableId = dynformAutoDTO.getTableId();
        List<DynformEnhanceJs> jsList = dynformEnhanceJsService.selectByTableIdAndJsType(tableId, "list");
        DynformEnhanceJs resJs = null;
        if (CollectionUtils.isNotEmpty(jsList)) {
            resJs = jsList.get(0);
        }

        String js = resJs != null ? resJs.getJs() : "";

        return UnifyResult.success().setData(DynfromEnhanceJsUtil.getJsStr(js));
    }

    @Override
    public List<DynformFieldDTO> getTableAllField(String tableId) {
        DynformFieldExample example = new DynformFieldExample();
        example.setOrderByClause("field_order ASC");
        example.createCriteria().andTableIdEqualTo(tableId);
        List<DynformField> dynformFields = dynformFieldMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(dynformFields)) {
            return new ArrayList<>();
        }

        final List<DynformFieldDTO> resList = new ArrayList<>();
        dynformFields.forEach(field -> resList.add(new DynformFieldDTO(field)));

        return resList;
    }


    private List<DynformField> getExistsFields(String tableId) {
        DynformFieldExample example = new DynformFieldExample();
        example.setOrderByClause("field_order ASC");
        example.createCriteria().andTableIdEqualTo(tableId);
        List<DynformField> dynformFields = dynformFieldMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(dynformFields)) {
            return new ArrayList<>();
        }

        return dynformFields;
    }

    private List<DynformField> getQueryFields(List<DynformField> existsFields) {
        List<DynformField> resList = new ArrayList<>();
        for (DynformField existsField : existsFields) {
            if (StringUtils.equals(existsField.getPageIsQuery(), DBYNEnum.Y.name())) {
                resList.add(existsField);
            }
        }
        return resList;
    }

    private List<DynformFieldDTO> getPageShowListFields(List<DynformFieldDTO> existsFields) {
        List<DynformFieldDTO> resList = new ArrayList<>();
        for (DynformFieldDTO existsField : existsFields) {
            if (StringUtils.equals(existsField.getFieldIsPk(), DBYNEnum.Y.name())) {
                resList.add(existsField);
                continue;
            }
            if (StringUtils.equals(existsField.getPageIsShowList(), DBYNEnum.Y.name())) {
                resList.add(existsField);
            }
        }
        return resList;
    }

    private List<DynformField> getPageShowFields(List<DynformField> existsFields, boolean includePk) {
        List<DynformField> resList = new ArrayList<>();
        for (DynformField existsField : existsFields) {
            if (includePk && StringUtils.equals(existsField.getFieldIsPk(), DBYNEnum.Y.name())) {
                resList.add(existsField);
                continue;
            }
            if (StringUtils.equals(existsField.getPageIsShow(), DBYNEnum.Y.name())) {
                resList.add(existsField);
            }
        }
        return resList;
    }

}
